/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

package org.apache.commons.exec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedOutputStream;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import org.apache.commons.exec.io.NullInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Copies standard output and error of sub-processes to standard output and
 * error of the parent process. If output or error stream are set to null, any
 * feedback from that stream will be lost.
 *
 */
public class DefaultProcessStreamHandler implements ProcessStreamHandler {
	private final static Logger LOGGER = LoggerFactory.getLogger(DefaultProcessStreamHandler.class);

	private final OutputStream out;
	private final OutputStream err;
	private final InputStream input;

	/** the last exception being caught */
	private IOException caught = null;

	private ScheduledExecutorService scheduledExecutorService;

	private Runnable processInputStreamBumper;
	private Runnable processErrorStreamBumper;
	private Runnable processOutputStreamPumper;

	private ScheduledFuture<?> processErrorStreamBumperFuture;
	private ScheduledFuture<?> processInputStreamBumperFuture;
	private ScheduledFuture<?> processOutputStreamPumperFuture;

	/**
	 * Construct a new <CODE>PumpStreamHandler</CODE>.
	 */
	public DefaultProcessStreamHandler() {
		this(System.out, System.err, new NullInputStream());
	}

	/**
	 * Construct a new <CODE>PumpStreamHandler</CODE>.
	 *
	 * @param outAndErr
	 *            the output/error <CODE>OutputStream</CODE>.
	 */
	public DefaultProcessStreamHandler(final OutputStream outAndErr) {
		this(outAndErr, outAndErr, new NullInputStream());
	}

	/**
	 * Construct a new <CODE>PumpStreamHandler</CODE>.
	 *
	 * @param out
	 *            the output <CODE>OutputStream</CODE>.
	 * @param err
	 *            the error <CODE>OutputStream</CODE>.
	 */
	public DefaultProcessStreamHandler(final OutputStream out, final OutputStream err) {
		this(out, err, null);
	}

	/**
	 * Construct a new <CODE>PumpStreamHandler</CODE>.
	 *
	 * @param out
	 *            the output <CODE>OutputStream</CODE>.
	 * @param err
	 *            the error <CODE>OutputStream</CODE>.
	 * @param input
	 *            the input <CODE>InputStream</CODE>.
	 */
	public DefaultProcessStreamHandler(final OutputStream out, final OutputStream err, final InputStream input) {
		this.out = out;
		this.err = err;
		this.input = input==null?new NullInputStream():input;
	}

	/**
	 * Set the <CODE>InputStream</CODE> from which to read the standard output of
	 * the process.
	 *
	 * @param is
	 *            the <CODE>InputStream</CODE>.
	 */
	@Override
	public void setProcessInputStream(final InputStream is) {
		if (out != null) {
			final boolean closeWhenExhausted = out instanceof PipedOutputStream ? true : false;
			processInputStreamBumper = new StreamPumper(is, out, closeWhenExhausted);
		}
	}

	/**
	 * Set the <CODE>InputStream</CODE> from which to read the standard error of the
	 * process.
	 *
	 * @param is
	 *            the <CODE>InputStream</CODE>.
	 */
	@Override
	public void setProcessErrorStream(final InputStream is) {
		if (err != null) {
			final boolean closeWhenExhausted = err instanceof PipedOutputStream ? true : false;
			processErrorStreamBumper = new StreamPumper(is, err, closeWhenExhausted);
		}
	}

	/**
	 * Set the <CODE>OutputStream</CODE> by means of which input can be sent to the
	 * process.
	 *
	 * @param os
	 *            the <CODE>OutputStream</CODE>. of process
	 */
	@Override
	public void setProcessOutputStream(final OutputStream os) {
		if (input != null) {
			if (input == System.in) {
				processOutputStreamPumper = new InputStreamPumper(input, os);
			} else {
				processOutputStreamPumper = new StreamPumper(input, os, true);
			}
		} else {
			try {
				os.close();
			} catch (final IOException e) {
				LOGGER.warn("Got exception while closing output stream", e);
			}
		}
	}

	/**
	 * Start the <CODE>Thread</CODE>s.
	 */
	@Override
	public void start() {
		this.processOutputStreamPumperFuture = this.scheduledExecutorService.schedule(this.processOutputStreamPumper, 10, TimeUnit.MILLISECONDS);
		this.processInputStreamBumperFuture = this.scheduledExecutorService.schedule(this.processInputStreamBumper, 10, TimeUnit.MILLISECONDS);
		this.processErrorStreamBumperFuture = this.scheduledExecutorService.schedule(this.processErrorStreamBumper, 10, TimeUnit.MILLISECONDS);
	}

	/**
	 * Stop pumping the streams. When a timeout is specified it it is not guaranteed
	 * that the pumper threads are cleanly terminated.
	 */
	@Override
	public void stop() throws IOException {
		try {
			processOutputStreamPumperFuture.cancel(true);
		} catch (Exception e1) {
			LOGGER.warn("stop process output error", e1);
		}
		try {
			processErrorStreamBumperFuture.cancel(true);
		} catch (Exception e1) {
			LOGGER.warn("stop process ERR error", e1);
		}
		try {
			processInputStreamBumperFuture.cancel(true);
		} catch (Exception e1) {
			LOGGER.warn("stop process input error", e1);
		}
		
		if (err != null && err != out) {
			try {
				err.flush();
			} catch (final IOException e) {
				LOGGER.warn("Got exception while closing output stream", e);
			}
		}

		if (out != null) {
			try {
				out.flush();
			} catch (final IOException e) {
				LOGGER.warn("Got exception while closing output stream", e);
			}
		}

		if (caught != null) {
			throw caught;
		}
	}

	
	public void setScheduledExecutorService(final ScheduledExecutorService scheduledExecutorService) {
		this.scheduledExecutorService = scheduledExecutorService;
	}
}
